<?php
// $Id$

/**
 * Controller_Users 控制器
 */
class Controller_Users extends Controller_Abstract
{

    function actionNameList() {
        $condi[] = new QDB_Expr(
            "username like '%" .$this->_context->user. "%'"
        );
        $users = User::find($condi)->limitPage($this->_context->page, 15)->query();

        $records = User::find($condi)->all()->getCount('user_id');
        //        dump($root->getConfig($childrens[0]));

        //                dump($articles);
        $this->_view['records'] = $records;
        $this->_view['pagesize'] = 15;
        $this->_view['users'] = $users;


    }

    function actionGetPass() {
        $mySelf = User::find('username = ? AND savecode = ?', $this->_context->username, $this->_context->savecode)->one()->query();
        if($mySelf -> id()) {
            $pass = FUNC::random(6);
            $mySelf->meta() -> changePassword($mySelf->username, $pass, null, 'true');
            //dump(Helper_Common::ini('smtp'));
            //dump(Helper_Common::ini('smtp/server'));
            $smtp = new smtp(Helper_Common::ini('smtp/server'), Helper_Common::ini('smtp/port'), true, Helper_Common::ini('smtp/user'), Helper_Common::ini('smtp/password'));
            //            $smtp -> debug = true;
            $smtp->sendmail($mySelf->fields->email, Helper_Common::ini('smtp/user'), Helper_Common::iniFront('sitename').'-取回密码通知', '您的登录密码是：'.$pass, 'HTML');
            return '密码邮件已发出，请尽快查看.';
        }
        else {
            return '您填写的信息不正确，请确认.';
        }

        //        if($mySelf -> checkPassword($this->_context->oldpass)) {
        //            $mySelf->meta() -> changePassword($mySelf->username, $this->_context->newpass, null, 'true');
        //            return $this->_redirectMessage('网站提示', "密码已修改", url('/profile'));
        //        }
    }



    function actionLogout() {
        Helper_RBAC::cleanAll();
        $referer = $this->_context->referer() ? $this->_context->referer() : url('');
        return $this->_redirectMessage('网站提示', '注销成功', $referer);
    }

    function actionUpdatePass() {
        $user = Helper_RBAC::get('user');
        $mySelf = User::find('user_id = ?', $user->user_id)->one()->query();
        if($mySelf -> checkPassword($this->_context->oldpass)) {
            $mySelf->meta() -> changePassword($mySelf->username, $this->_context->newpass, null, 'true');
            return $this->_redirectMessage('网站提示', "密码已修改", url('/profile'), 'error');
        }
        return $this->_redirectMessage('网站提示', "旧密码不正确,请确认", url('/profile'), 'error');
    }

    function actionIndex()
    {
        FUNC::getChildren(Column::getFormCache(null, $this->_context->col_id), $childrens, array('col_id'), false);    //查找孩子
        FUNC::getParent(Column::getFormCache(), $this->_context->col_id, $paths, array('name'), false);    //查找父亲
        //        dump($parents);
        FUNC::formatArrayKey($paths);

        $childrens[] = $this->_context->col_id;
        FUNC::formatArrayKey($childrens);
        $condi[] = new QDB_Expr(
            'col_id in ( '.implode(',', $childrens).' )'
        );

//        if($this->_context->group_id) {
//            $condi[] = new QDB_Cond(
//            'role_id = ?', $this->_context->group_id
//            );
//            $group = Role::getFormCache(null, $this->_context->group_id);
//            //            dump($group);
//        }

        if($this->_context->keyword) {
            $condi[] = new QDB_Expr(
            "title like '%{$this->_context->keyword}%'"
            );
        }

        $user = Helper_RBAC::get('user');
        $condi[] = new QDB_Cond(
            "user_id = ? ", $user->user_id
        );

        //                dump($condi);
        $page = $this->_context->page;
        $pagesize = Helper_Common::iniFront('article/pagesize');
        //        $pagesize = Q::ini('appini/background/column_list_pagesize');
        $articles = Article::find($condi)->limitPage($page, $pagesize)->order('created DESC')->query();
        $records = Article::find($condi)->all()->getCount('art_id');

        $column = Column::find('col_id = ?', $childrens[0])->one()->query();

        //        dump($root->getConfig($childrens[0]));
        $config = $column->getConfig($childrens[0]);

        //                dump($articles);
        $this->_view['records'] = $records;
        $this->_view['pagesize'] = $pagesize;
        $this->_view['articles'] = $articles;

        $this->_view['paths'] = $paths;
        $this->_view['group'] = $group;
    }

    function actionSendmsg() {
        if($this->_context->to) {
            $condi[] = new QDB_Expr(
            'user_id in(' .FUNC::getIdset($this->_context->to, null, false). ')'
            );
            //        dump($condi);
            $users = User::find($condi)->all()->query()->toArray();
            $users = implode(',', FUNC::setArrayByField(array('username'), $users, false));
            //                                dump($users);

        }

        $this->_view['receivers'] = $users;
    }

    function actionViewMsg() {
        $user =  Helper_Rbac::get('user');
        $condi[] = new QDB_Cond('msg_id = ?', $this->_context->msg_id);
        //        dump($view_users_acc);
        $message = Message::find($condi)->one()->query();
        $view_users_acc = $message->meta()->assoc('view_users');
        $view_users_acc->on_find_where = array('msg_id'=>$this->_context->msg_id, 'user_id' => $user->user_id);
        //        $message->meta()->updateDbWhere(new QDB_Expr('views = views + 1'), 'art_id = ?', $this->_context->art_id);

        //            $message->meta()->on_find_where = array('user_id'=>$user->user_id, 'msg_id'=>$this->_context->msg_id);
        //        dump($message->view_users->find('user_id=4'));
        //        $condi = null;
        //        $condi[]= new QDB_Cond(
        //            '[view_users.user_id] = ?', $user->user_id
        //        );
        //        dump($message->view_users);
        //        $condi[]= new QDB_Cond(
        //            '[view_users.msg_id] = ?', $this->_context->msg_id
        //        );
        //        $view_users = Message::find('[view_users.msg_id]=?', $this->_context->msg_id)->all()->query();
        //        dump($view_users);
        if(!$message->view_users->id() && $message->user_id != $user->user_id) {
            $row = array(
                'user_id' => $user->user_id,
            );
            $message->view_users[] = new UsersReadMessages($row);
        }
        $message -> save();

        //        $view_users_acc->on_find_where = array('msg_id'=>4);

        Helper_Cache::clear(Helper_Common::iniFront('counter_cache'));
        $this->_view['message'] = $message;
    }

    function actionAddressList() {
        if($this->_context->depart_id) {
            $condi[] = new QDB_Cond(
         'depart_id = ?',  $this->_context->depart_id
            );
        }
        $page = $this->_context->page;
        $pagesize = 20;
        $users = User::find($condi)->limitPage($page, $pagesize)->order('created DESC')->query();
        $records = User::find($condi)->all()->getCount();
        $this->_view['records'] = $records;
        $this->_view['pagesize'] = $pagesize;
        //        dump($addresslists);
        $this->_view['users'] = $users;
    }

    function actionLogin()
    {
        $form = new Form_UserLogin(url('users/login'));
        $form->_subject = '登录';
        if ($this->_context->isPOST() && $form->validate($_POST))
        {
            FUNC::dsetcookie(Q::ini('acl_session_key').'loginuser', $form['username']->value, 3156000);

            try
            {
                // 使用 acluser 插件的 validateLogin() 方法验证登录并取得有效的 user 对象
                $user = User::meta()->validateLogin($form['username']->value, $form['password']->value);
                // 将登录用户的信息存入 SESSION，以便应用程序记住用户的登录状态
                //            dump($user->roles);
                //                $this->_app->changeCurrentUser($user->aclData(), 'MEMBER');

                //dump($user->roles->toArray());

                //                dump(FUNC::setArrayByField(array('role_id'), $user->roles->toArray()));
                //            dump($user->aclRoles());
                Helper_RBAC::change('user', $user->aclData(), $user->aclRoles());

                // 登录成功后，重定向浏览器
                //                return $this->_redirect(url('default/index'));
                return $this->_redirect(url('articles/one'));
            }
            catch (AclUser_UsernameNotFoundException $ex)
            {
                return $this->_redirectMessage('网站提示', "您输入的用户名 {$form['username']->value} 不存在", url('/login'), 'error');

                //$form['username']->invalidate("您输入的用户名 {$form['username']->value} 不存在");
            }
            catch (AclUser_WrongPasswordException $ex)
            {
                return $this->_redirectMessage('网站提示', "您输入的密码不正确", url('/login'), 'error');

                //$form['password']->invalidate("您输入的密码不正确");
            }
        }

        $this->_view['form'] = $form;
        $this->_viewname = 'login';
    }

    function actionProfile() {
        $user = Helper_RBAC::get('user');
        if($this->_context->isPost()) {
            //            echo 'aaaaa';
            $profile = User::find('user_id = ?', $user->user_id)->one()->query();

            $f = date("Y-m-d") . "/";	//上传下级文传夹
            $upload = new LZW_UPLOAD(true, "attachments/", $f);
            //            $upload -> session_id = session_id();
            if($upload -> doupload() && $upload -> filecount > 0) {
                foreach($upload -> filepaths as $key => $filepath) {
                    $profile->fields->photo = $filepath;
                }
            }
            //            $_SESSION['error'] = $upload -> err;

            $profile -> fields -> sex = $this->_context->sex;
            $profile -> fields -> telephone = $this->_context->telephone;
            $profile -> fields -> birth = $this->_context->birth;
            $profile -> fields -> qq = $this->_context->qq;
            $profile -> fields -> email = $this->_context->email;
            $profile -> fields -> address = $this->_context->address;
            $profile->save();
            return $this->_redirectMessage('网站提示', '更新成功', url('/profile'));
        }

        $this->_view['user'] = $user;
    }

    function actionEditPost() {
        $user = Helper_RBAC::get('user');
        $article = Article::find('art_id = ?', $this->_context->art_id)->one()->query();
        if($article -> id()) {
            FUNC::getParent(Column::getFormCache(), $article->col_id, $parents, array('col_id'));    //查找父亲
            FUNC::getChildren(Column::getFormCache(null, $article->col_id), $childrens, array('col_id'));    //查找父亲
            $column = Column::find('col_id = ?', $article->col_id)->one()->query('fields');
        }
        else {
            //            echo 'aa';
            //            dump(Column::getFormCache());
            //            exit;
            FUNC::getParent(Column::getFormCache(), $this->_context->col_id, $parents, array('col_id'));    //查找父亲

            //            exit;

            FUNC::getChildren(Column::getFormCache(null, $this->_context->col_id), $childrens, array('col_id'));    //查找父亲
            $column = Column::find('col_id = ?', $this->_context->col_id)->one()->query('fields');
        }
        //        unset($parents[0]);
        FUNC::formatArrayKey($parents);
        FUNC::formatArrayKey($childrens);
        //        dump($parents);
        //        dump($childrens);
        //        exit;
        //        dump($column->fields->column->config);
        //        $this->
        //        dump($column->fields->column->config);
        //        dump(Q::ini('session_cookie_name'));
        //        dump($this->_app);
        //        dump($_SESSION);
        $paths = $column->path($this->_context->col_id);

        $this->_view['parents_array'] = $parents;
        $this->_view['childrens_array'] = $childrens;
        $this->_view['subject'] = '发布';
        $this->_view['article'] = $article;
        $this->_view['user'] = $user;
        $this->_view['paths'] = $paths;

        //        dump($article->photoes);
        $this->_viewname = $column->getConfig($column->col_id)->template['viewname']['edit'];
    }

    function actionMessages() {
        //        dump(Q::ini('appini'));
        $user = Helper_RBAC::get('user');
        if($this->_context->target == 'in'){
            $condi[] = new QDB_Cond(
            '[to_users.user_id] = ? AND [to_users.receiver_del] = 0', $user->user_id
            );
            //            $condi[] = new QDB_Cond(
            //            'hasremove = ?', 0
            //            );
            //            if($this->_context->new) {
            //                $condi[] = new QDB_Cond(
            //            '[users.art_id] != ?', $user->user_id
            //                );
            //            }
        }
        else {
            //            $condi[] = new QDB_Cond(
            //            '[to_users.sender_del] = 0'
            //            );
            $condi[]  = new QDB_Cond(
            '[user_id] = ?', $user->user_id
            );
            $condi[] = new QDB_Cond(
                        'hasremove = ?', 0
            );
        }
        //        dump($condi);

        $page = $this->_context->page;
        $pagesize = 20;
        $messages = Message::find($condi)->limitPage($page, $pagesize)->order('created DESC')->query();
        $records = Message::find($condi)->all()->getCount();

        $this->_view['messages'] = $messages;
        $this->_view['records'] = $records;
        $this->_view['pagesize'] = $pagesize;
        $this->_view['user'] = $user;

        if($this->_context->target == 'in'){
            $this->_viewname = 'in-msg';
        }
        else {
            $this->_viewname = 'out-msg';
        }

    }

    function actionRemoveMsg() {
        $user = Helper_RBAC::get('user');
        $idset = FUNC::getIdset($this->_context->idset);
        $target = $this->_context->target;
        foreach($idset as $id) {

            $record = Message::find('msg_id = ?', $id)->one()->query();
            if($target == 'in') {
                $row = array(
                    'user_id' => $user->user_id,
                    'receiver_del' => 1,
                );
            }
            else {
                $row = array(
                    'user_id' => $user->user_id,
                    'sender_del' => 1,
                );
                $record -> hasremove = 1;
            }
            $to = new MessagesToUsers($row);
            $record -> to_users[] = $to;
            $record -> save();
        }
        $referer = $this->_context->referer() ? $this->_context->referer() : url('/messages');
        Helper_Cache::clear(Helper_Common::iniFront('counter_cache'));

        return $this->_redirectMessage('网站提示', '删除成功', $referer);
    }

    function actionSaveMsg() {
        $user = Helper_Rbac::get('user');
        $message = Message::find('msg_id = ?', $this->_context->msg_id)->one()->query();

        $user_names = explode(',', FUNC::getV('receiver'));
        //        dump($user_names);
        foreach($user_names as $key=> $name) {
            $condi = new QDB_Cond(
            'username = ?', $name
            );
            //                    dump($condi);
            $to_user = User::find($condi)->one()->query();
            if(!$to_user->id()) continue;
            $message->users[] = $to_user;
            //            dump($to_user);
        }

        if($message->id()) {
        }
        else {
            $message -> user_id = $user -> user_id;
        }
        //        $message -> role_id = $this->_context->group_id;
        //        $message -> col_id = $this->_context->parent;
        $message -> title = $this->_context->title;
        $message -> content = $this->_context->content;
        $message -> save();
        Helper_Cache::clear(Helper_Common::iniFront('counter_cache'));

        //        dump($message);
        return json_encode($message->toArray());
    }



    function actionSaveArticle() {
        $user = Helper_Rbac::get('user');
        $article = Article::find('art_id = ?', $this->_context->art_id)->one()->query();
        if($article->id()) {
        }
        else {
            $article -> user_id = $user -> user_id;
//            $roles = FUNC::setArrayByField(array('role_id'), $user->roles, false);
            //            $article -> role_id = $roles[0];
        }
        $article -> depart_id = $this->_context->depart_id;

        $article -> col_id = $this->_context->parent;
        $article -> title = $this->_context->title;
        $article -> post -> content = $this->_context->content;

        if($_FILES) {
            $f = date("Y-m-d") . "/";	//上传下级文传夹
            $upload = new LZW_UPLOAD(true, "attachments/", $f);
            //            $upload -> session_id = session_id();
            if($upload -> doupload() && $upload -> filecount > 0) {
                foreach($upload -> filepaths as $key => $filepath) {
                    foreach($upload -> filepaths as $key => $filepath) {
                        $row = array(
                    'art_id' => $article->art_id,
                    'url' => $filepath,
                    'size' => $upload->files['size'][$key],
                    'type' => $upload->files['type'][$key],
                    'name' => $upload->filenames[$key],
                     'user_id' => $article->user_id,
                        );
                        $photo = new Articlephoto($row);
                        $article -> photoes[] = $photo;
                    }
                }
            }
        }
        //            $_SESSION['error'] = $upload -> err;


        $article -> save();

        $attachs = FUNC::getIdset(FUNC::getV('idset'));
        if($attachs) {
            foreach($attachs as $att_id) {
                $attachment = Attachment::find('att_id = ?', $att_id)->one()->query();
                if($attachment -> id()) {
                    $attachment -> remove();
                }
            }
        }

        $article->meta()->removeAssoc('photoes');
        $article->post->content = h($article->post->content);
        //                dump(json_encode($article->toArray()));
        return json_encode($article->toArray());
    }

    /**
     * 上传并保存附件
     */
    function actionUPLOAD() {
        if (isset($_POST["PHPSESSID"])) {
            session_id($_POST["PHPSESSID"]);
        }
        $_SESSION['POST'] =$_POST;
        $_SESSION['files']=$_FILES;
        if($_FILES) {
            $f = date("Y-m-d") . "/";	//上传下级文传夹
            $upload = new LZW_UPLOAD(true, "attachments/", $f);
            $upload -> session_id = session_id();
            #isset($_POST['upfile']) && 		//上传后要更新的控件
            if($upload -> doupload() && $upload -> filecount > 0) {
                foreach($upload -> filepaths as $key => $filepath) {
                    $row = array(
                    'art_id' => $_POST['art_id'],
                    'url' => $filepath,
                    'size' => $upload->files['size'][$key],
                    'type' => $upload->files['type'][$key],
                    'name' => $upload->filenames[$key],
                    'extname' => $upload->filetypes[$key],
                    );
                    $attachment = new Attachment($row);
                    $attachment->save();
                }
            }
            $_SESSION['error'] = $upload -> err;
        }

    }

    function actionUploadMsgAttachments() {
        if (isset($_POST["PHPSESSID"])) {
            session_id($_POST["PHPSESSID"]);
        }
        $_SESSION['POST'] =$_POST;
        $_SESSION['files']=$_FILES;
        if($_FILES) {
            $f = date("Y-m-d") . "/";	//上传下级文传夹
            $upload = new LZW_UPLOAD(true, "attachments/", $f);
            $upload -> session_id = session_id();
            #isset($_POST['upfile']) && 		//上传后要更新的控件
            if($upload -> doupload() && $upload -> filecount > 0) {
                foreach($upload -> filepaths as $key => $filepath) {
                    $row = array(
                    'msg_id' => $_POST['msg_id'],
                    'url' => $filepath,
                    'size' => $upload->files['size'][$key],
                    'type' => $upload->files['type'][$key],
                    'name' => $upload->filenames[$key],
                    'extname' => $upload->filetypes[$key],
                    );
                    $attachment = new Msgattachment($row);
                    $attachment->save();
                }
            }
            $_SESSION['error'] = $upload -> err;
        }
    }

    function actionSavecode() {
        $user = Helper_RBAC::get('user');
        if($this->_context->savecode) {
            User::meta()->updateDbWhere(new QDB_Expr('savecode = '.$this->_context->savecode), 'user_id = ?', $user->user_id);
            return $this->_redirectMessage('网站提示', '修改完成', FUNC::referer());
        }
        else {
            return $this->_redirectMessage('网站提示', '安全码不能为空', FUNC::referer(), 'error');
        }
    }


    function actionCreateRoles() {
//                $articles = Article::find()->all()->query();
//                foreach($articles as $article) {
//                            if(!$article->depart_id) continue;
//                            QDB::getConn()->execute('update oa_users set depart_id = '.$article->depart_id. ' WHERE user_id='.$article->user_id);
//                }
                $users = User::find()->all()->query();
                foreach($users as $user) {
                    QDB::getConn()->execute('update `oa_articles` set depart_id = '.$user->depart_id. ' WHERE user_id='.$user->user_id);
                }
    }

}


